// Augment Code Tool System Demo
// 演示如何使用还原的工具系统

import { ToolManager } from './core/tool-manager';
import { ToolCategory } from './core/interfaces';

/**
 * 演示工具系统的使用
 */
async function demo() {
    console.log('🚀 Augment Code Tool System Demo\n');

    // 创建工具管理器
    const toolManager = new ToolManager();

    try {
        // 1. 初始化工具系统
        console.log('📦 Initializing tool system...');
        await toolManager.initialize();
        console.log('✅ Tool system initialized successfully\n');

        // 2. 显示可用工具
        console.log('🔧 Available tools:');
        const availableTools = toolManager.getAvailableTools();
        availableTools.forEach(tool => console.log(`   - ${tool}`));
        console.log('');

        // 3. 按类别显示工具
        console.log('📂 Tools by category:');
        const fileTools = toolManager.getToolsByCategory(ToolCategory.FILE_OPERATIONS);
        const processTools = toolManager.getToolsByCategory(ToolCategory.PROCESS_MANAGEMENT);

        console.log(`   File Operations (${fileTools.length}): ${fileTools.join(', ')}`);
        console.log(`   Process Management (${processTools.length}): ${processTools.join(', ')}`);
        console.log('');

        // 4. 演示文件操作
        console.log('📝 Demo: File Operations');

        // 创建一个测试文件
        const testContent = `# Test File
This is a demonstration of the Augment Code tool system.

## Features
- File operations (read, write, edit)
- Process management
- Tool registration and execution
- Error handling

Generated at: ${new Date().toISOString()}
`;

        console.log('   Creating test file...');
        const saveResult = await toolManager.executeTool('save-file', {
            path: './demo-output.md',
            content: testContent
        });

        if (saveResult.success) {
            console.log('   ✅ File created successfully');
        } else {
            console.log('   ❌ Failed to create file:', saveResult.error?.message);
        }

        // 读取文件
        console.log('   Reading test file...');
        const readResult = await toolManager.executeTool('read-file', {
            path: './demo-output.md'
        });

        if (readResult.success) {
            console.log('   ✅ File read successfully');
            console.log(`   📄 File size: ${readResult.data.size} bytes`);
        } else {
            console.log('   ❌ Failed to read file:', readResult.error?.message);
        }

        // 5. 演示进程管理
        console.log('\n⚙️  Demo: Process Management');

        console.log('   Executing simple command...');
        const processResult = await toolManager.executeTool('launch-process', {
            command: 'echo "Hello from Augment Code Tool System!"',
            wait: true,
            max_wait_seconds: 10,
            cwd: process.cwd()
        });

        if (processResult.success) {
            console.log('   ✅ Command executed successfully');
            console.log(`   📤 Output: ${processResult.data.output.trim()}`);
            console.log(`   ⏱️  Execution time: ${processResult.data.execution_time}ms`);
        } else {
            console.log('   ❌ Command execution failed:', processResult.error?.message);
        }

        // 6. 演示字符串替换
        console.log('\n✏️  Demo: String Replace Editor');

        const replaceResult = await toolManager.executeTool('str-replace-editor', {
            path: './demo-output.md',
            old_str: 'Generated at: ' + new Date().toISOString(),
            new_str: 'Generated at: ' + new Date().toISOString() + '\nUpdated by: Augment Code Tool System',
            old_str_start_line_number: 10,
            old_str_end_line_number: 10
        });

        if (replaceResult.success) {
            console.log('   ✅ String replacement successful');
            console.log(`   📝 Lines replaced: ${replaceResult.data.linesReplaced}`);
        } else {
            console.log('   ❌ String replacement failed:', replaceResult.error?.message);
        }

        // 7. 显示工具统计
        console.log('\n📊 Tool Statistics:');
        const stats = toolManager.getToolStats();
        console.log(`   Total tools: ${stats.totalTools}`);
        console.log(`   Enabled tools: ${stats.enabledTools}`);
        console.log(`   Categories: ${Object.keys(stats.categories).join(', ')}`);

        if (stats.mostUsedTools.length > 0) {
            console.log('   Most used tools:');
            stats.mostUsedTools.forEach((tool: any) => {
                console.log(`     - ${tool.name}: ${tool.callCount} calls`);
            });
        }

        // 8. 演示错误处理
        console.log('\n🚨 Demo: Error Handling');

        console.log('   Testing invalid tool name...');
        try {
            await toolManager.executeTool('non-existent-tool', {});
        } catch (error) {
            console.log('   ✅ Error caught correctly:', error instanceof Error ? error.message : `${error}`);
        }

        console.log('   Testing invalid parameters...');
        const invalidResult = await toolManager.executeTool('read-file', {
            // 缺少必需的 path 参数
        });

        if (!invalidResult.success) {
            console.log('   ✅ Parameter validation working:', invalidResult.error?.message);
        }

        console.log('\n🎉 Demo completed successfully!');

    } catch (error) {
        console.error('❌ Demo failed:', error instanceof Error ? error.message : `${error}`);
    } finally {
        // 清理资源
        console.log('\n🧹 Cleaning up...');
        await toolManager.cleanup();
        console.log('✅ Cleanup completed');
    }
}

/**
 * 显示系统信息
 */
function showSystemInfo() {
    console.log('🔍 System Information:');
    console.log(`   Node.js version: ${process.version}`);
    console.log(`   Platform: ${process.platform}`);
    console.log(`   Architecture: ${process.arch}`);
    console.log(`   Working directory: ${process.cwd()}`);
    console.log('');
}

// 运行演示
showSystemInfo();
demo().catch(error => {
    console.error('Demo execution failed:', error);
    process.exit(1);
});
